package com.gyt.framework.common.utils;

import com.alibaba.fastjson.JSON;
import org.apache.tomcat.util.codec.binary.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author created by v_yantgao
 * @Date 2021/1/6 19:26
 */
public class RenderUtil {

    private static Logger logger = LoggerFactory.getLogger(RenderUtil.class);

    /**
     * 渲染json结果
     *
     * @param response
     * @param jsonStr
     */
    public static void renderFlatJSON(HttpServletResponse response, Object jsonStr) {
        try {
            response.setContentType("application/json;charset=UTF-8");
            ServletOutputStream os = response.getOutputStream();
            os.write(StringUtils.getBytesUtf8(jsonStr == null ? "{}" : jsonStr.toString()));
            os.flush();
        } catch (Exception ex) {
            logger.error("render json error", ex);
        }
    }

    /**
     * 渲染json结果
     *
     * @param response
     * @param result
     */
    public static void renderJSON(HttpServletResponse response, Object result) {
        renderFlatJSON(response, JSON.toJSONString(result));
    }

}
